//
//  PictureViewController.m
//  PIC
//
//  Created by luffy on 14-10-21.
//  Copyright (c) 2014年 panchuyou. All rights reserved.
//

#import "PictureViewController.h"
#import "HotTableViewCell.h"
#import "HotModel.h"
#import "MJRefresh.h"
#import "AFHTTPRequestOperationManager.h"
#import "SettingViewController.h"
#define HOT_URL @"http://c.m.163.com/photo/api/list/0096/54GI0096.json"
#import "UIView+WebCacheOperation.h"
#import "PicturePhotoViewController.h"
static int alertnum = 1;

@interface PictureViewController () <PicturePhotoViewControllerDelegate>
@property (nonatomic, retain) NSMutableArray * hotContentArray;
@property (nonatomic, retain) NSString * cellNumber;
@property (nonatomic, retain) NSString * setidNumber;
@property (nonatomic, retain) NSMutableArray * array;
@end

@implementation PictureViewController
- (void)dealloc
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    [_hotContentArray release];
    [_cellNumber release];
    [_setidNumber release];
    [_array release];
    [super dealloc];
}

- (void)viewWillAppear:(BOOL)animated
{
    if (alertnum == 1) {
        
    [super viewWillAppear:YES];
        UIAlertView * alter = [[UIAlertView alloc]initWithTitle:@"提示" message:@"在2G/3G网络下图片会产生大量流量,建议在WIFI网络下浏览" delegate:self cancelButtonTitle:@"我知道了" otherButtonTitles:nil];
        [alter show];
        [alter release];
        alertnum = 0;
        }
}

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        self.view.frame = [UIScreen mainScreen].bounds;
        // Custom initialization
        _hotContentArray = [[NSMutableArray alloc] init];
        self.navigationItem.title = @"LPSNews";
        _cellNumber = [[NSString alloc] init];
        _setidNumber = [[NSString alloc] init];
        _array = [[NSMutableArray alloc] init];
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        UIBarButtonItem * rightBtn = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Setting_icon"] style:UIBarButtonItemStyleBordered target:self action:@selector(setting)];
        [rightBtn setTintColor:[UIColor whiteColor]];
        self.navigationItem.rightBarButtonItem = rightBtn;
    }
    return self;
}
- (void)setting
{
    SettingViewController * settingVC  = [[[SettingViewController alloc] init]autorelease];
    [self.navigationController pushViewController:settingVC animated:YES];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    UIColor * color = [UIColor whiteColor];
    [self requestWebDataForURLString:HOT_URL andIsDowndrag:YES];
    NSDictionary * dict = [NSDictionary dictionaryWithObject:color forKey:NSForegroundColorAttributeName];
    self.navigationController.navigationBar.titleTextAttributes = dict;
    
    [self.tableView addHeaderWithTarget:self action:@selector(headerUpdata)];
    [self.tableView addFooterWithTarget:self action:@selector(footUpdata)];

}

- (void)headerUpdata
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
        [self requestWebDataForURLString:HOT_URL andIsDowndrag:YES];
    });
}

- (void)footUpdata
{
    int number1 = [self setidNumberForArray:_hotContentArray];
    int number2 = [self cellNumberForArray:_hotContentArray];
    NSString * temStr = [NSString stringWithFormat:@"/%d",number1 - number2];
    NSMutableString * URLStr = [[NSMutableString alloc] initWithString:HOT_URL];
    [URLStr insertString:temStr atIndex:[HOT_URL length]- 5];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
        [self requestWebDataForURLString:URLStr andIsDowndrag:NO];
    });
}

- (int)setidNumberForArray:(NSMutableArray *)mutableArray
{
    int number = 0;
    for (int i = 0 ; i < 1; i ++) {
        HotModel * hot = [mutableArray objectAtIndex:_hotContentArray.count - 1];
        number = [hot.setid intValue];
    }
    return number;
}

- (int)cellNumberForArray:(NSMutableArray *)mutableArray
{
    NSInteger numberint = mutableArray.count;
    NSString * numberStr = [NSString stringWithFormat:@"%ld",(long)numberint];
    int number = [numberStr intValue];
    return number;
}

- (void)tableViewDownLoadDataForURLString:(NSString *)urlstring andIsDowndrag:(BOOL)isDowndrag
{
    if (_hotContentArray == nil) {
        
        _hotContentArray = [[NSMutableArray alloc] init] ;
        
        [self requestWebDataForURLString:urlstring andIsDowndrag:isDowndrag];
    }
}


- (void)requestWebDataForURLString:(NSString *)urlstring andIsDowndrag:(BOOL)isDowndrag
{
    
    NSMutableArray *requestDataArray = [[NSMutableArray alloc] init];
    AFHTTPRequestOperationManager *requestManager = [AFHTTPRequestOperationManager manager];
    
    [requestManager GET:urlstring  parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSArray *temArray = responseObject;

        for (NSDictionary * dic in temArray) {
            HotModel * hot = [[HotModel alloc] init];
            [hot setValuesForKeysWithDictionary:dic];
            [requestDataArray addObject:hot];
            [hot release];
        }
        if (isDowndrag) {

            self.hotContentArray = requestDataArray;
            [self.tableView headerEndRefreshing];

        }else
        {
            self.hotContentArray = requestDataArray;
            [self.tableView footerEndRefreshing];
        }

        [self.tableView reloadData];
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
       
        UILabel *textLable = [[UILabel alloc] init];
        textLable.frame = CGRectMake(0, 0, 140, 100);
        textLable.center = CGPointMake(160, 240);
        textLable.backgroundColor = [UIColor darkGrayColor];
        textLable.text = @"网络不给力";
        textLable.textColor = [UIColor whiteColor];
        textLable.textAlignment = NSTextAlignmentCenter;
        textLable.layer.cornerRadius = 8;
        textLable.layer.masksToBounds = YES;
        [self.view.window addSubview:textLable];
        textLable.alpha = 0;
        [UIView animateWithDuration:0.1 animations:^{
            [UIView animateWithDuration:0.1 delay:0.2 options:UIViewAnimationOptionCurveLinear animations:^{
                textLable.alpha = 0.8;
            } completion:^(BOOL finished) {
                [UIView animateWithDuration:0.5 delay:1 options:UIViewAnimationOptionCurveLinear animations:^{
                    textLable.alpha = 0;
                } completion:^(BOOL finished) {
                    [textLable removeFromSuperview];
                }];
            }];
        }];

        [textLable release];

        [self.tableView headerEndRefreshing];
        [self.tableView footerEndRefreshing];
        
    }];
    
    [requestDataArray release];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(_delegate && [_delegate respondsToSelector:@selector(pictureViewControllerCancelSwipeGesture)])
    {
        [_delegate pictureViewControllerCancelSwipeGesture];
    }
    
    
    PicturePhotoViewController * hotVC = [[PicturePhotoViewController alloc] init];
    HotModel * hot = [_hotContentArray objectAtIndex:indexPath.row];
    hotVC.setid = hot.setid;
    hotVC.delegate = self;
    [self.navigationController pushViewController:hotVC animated:YES];
    [hotVC release];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _hotContentArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *techCellStr = @"cell";
    
    HotTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:techCellStr];
    
    if (cell == nil) {
        
        cell = [[[HotTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:techCellStr] autorelease];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    cell.hotImageView.image = nil;
    cell.titleLabel.text = nil;
    
    HotModel *hotData = _hotContentArray[indexPath.row];
    hotData.number = indexPath.row;
    cell.hot = hotData;
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 240;
}


- (void)picturePhotoViewControllerOpenSwipeGesture
{
    if(_delegate && [_delegate respondsToSelector:@selector(pictureViewControllerOpenSwipeGesture)])
    {
        [_delegate pictureViewControllerOpenSwipeGesture];
    }
    
}

/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
 {
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
 } else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }
 }
 */

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
 {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
